package org.laowenchao.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.TimeZone;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.laowenchao.client.model.Track;
import org.laowenchao.client.rpc.PositionService;
import org.laowenchao.dao.BaseDao;
import org.laowenchao.dao.CellTowerInfoDao;
import org.laowenchao.dao.GSMPositionDao;
import org.laowenchao.dao.MyGSMPositionDao;
import org.laowenchao.pojo.CellTowerInfo;
import org.laowenchao.pojo.GSMPosition;
import org.laowenchao.pojo.MyGSMPosition;
import org.laowenchao.tool.TimeFormat;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class PositionServiceImpl extends RemoteServiceServlet implements PositionService{


	private static final long serialVersionUID = 2225959701375610485L;
	final static long TOWER_LASTS_TIME =604800000;//7*24*60*60*1000 ;
	final static int MAX_LIST_SIZE = 100;
	static LinkedList<String> writableCellList = new LinkedList<String>();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		String key = req.getParameter("k");
		if("old".equals(key))
		{
			String cellId = req.getParameter("cellid");
			String lac = req.getParameter("lac");
			String lat = req.getParameter("lat");
			String lon = req.getParameter("lon");
			String p = req.getParameter("p");
			if(Integer.parseInt(cellId)>0)
			{

				Date date = Calendar.getInstance(TimeZone.getTimeZone("GMT+8")).getTime();
				GSMPosition position = new GSMPosition(cellId,lac,lat,lon,p,date);


				boolean b = new BaseDao().addObject(position);

				int nextTime = 5;

				resp.getWriter().write(nextTime+" "+b);
			}	
		}
		else if("record".equals(key))
		{
			String cellId = req.getParameter("cellid");
			String lac = req.getParameter("lac");
			if(Integer.parseInt(cellId)>0)
			{
				MyGSMPosition position = new MyGSMPosition(cellId,lac,new Date());
				boolean b = new BaseDao().addObject(position);
				CellTowerInfoDao cellDao = new CellTowerInfoDao();		
				CellTowerInfo towerInfo=cellDao.getInfo(cellId, lac);
				if(towerInfo==null||System.currentTimeMillis()-towerInfo.getRefreshTime().getTime()>TOWER_LASTS_TIME)
				{
					resp.getWriter().write(0);
					writableCellList.addFirst(cellId);
					if(writableCellList.size()>MAX_LIST_SIZE)
						writableCellList.removeLast();
					
				}
				else
				{
					resp.getWriter().write(1);	
				}

			}
		}	
		else if("refresh".equals(key))
		{	
			String cellId = req.getParameter("cellid");
			String lac = req.getParameter("lac");
			String lat = req.getParameter("lat");
			String lon = req.getParameter("lon");
			String p = req.getParameter("p");
			if(Integer.parseInt(cellId)>0&&writableCellList.contains(cellId))
			{
				//System.out.println("!!!"+writableCellList.size());
				writableCellList.remove(cellId);
				CellTowerInfoDao cellDao = new CellTowerInfoDao();	
				CellTowerInfo oldTowerInfo=cellDao.getInfo(cellId, lac);
				if(oldTowerInfo==null)
				{
					CellTowerInfo towerInfo = new CellTowerInfo(cellId,lac,lat,lon,p,new Date());
					boolean b = new BaseDao().addObject(towerInfo);
					if(b)
						resp.getWriter().write(1);
					else
						resp.getWriter().write(0);
					
				}
				else
				{
					oldTowerInfo.setLat(lat);
					oldTowerInfo.setLon(lon);
					oldTowerInfo.setPosition(p);
					oldTowerInfo.setRefreshTime(new Date());
					boolean b = new BaseDao().updateObject(oldTowerInfo);
				}				
			}
			
		}
	}
	
	

	@Override
	public List<Track> getTrackByDate(Date date) {
		GSMPositionDao gsmDao = new GSMPositionDao();
		List<GSMPosition> list  = gsmDao.getTracksByDate(date);
		List tracks = new ArrayList<Track>();
		for(int i=0;i<list.size();i++)
		{
			GSMPosition p = list.get(i);
			tracks.add(new Track(TimeFormat.formatTime(p.getDate()),p.getLat(),p.getLon(),p.getPosition()));
		}
		
		return tracks;
	}
	
	
	@Override
	public List<Track> getTrackByDate2(Date date) {
		
		MyGSMPositionDao myGsmDao = new MyGSMPositionDao();
		CellTowerInfoDao towerDao = new CellTowerInfoDao();
		List<MyGSMPosition> list  = myGsmDao.getTracksByDate(date);
		List tracks = new ArrayList<Track>();
		for(int i=0;i<list.size();i++)
		{
			MyGSMPosition p = list.get(i);
			CellTowerInfo towerInfo = towerDao.getInfo(p.getCellId(), p.getLAC());
			if(towerInfo!=null)
				tracks.add(new Track(TimeFormat.formatTime(p.getDate()),towerInfo.getLat(),towerInfo.getLon(),towerInfo.getPosition()));
			else
				tracks.add(new Track(TimeFormat.formatTime(p.getDate()),"unknown","unknown","unknown"));
		}
		
		return tracks;
	}

//	private boolean isTowerRecordExist()
//	{
//		
//	}

}
